<?php if (!defined("BASEPATH")) exit("No direct script access allowed"); ?>

<? // Common::pr($getMessage ); exit; ?>

<script type="text/javascript">
	Ext.onReady(function() {

		var winMessages; // edit ablak
		var messageForm; // form panel

		var reader = new Ext.data.ArrayReader({}, [
			{name: 'mesId'},
			{name: 'mesUniqueId'},
			{name: 'mesSenderUsrId'},
			{name: 'mesInsId'},
			{name: 'mesReaderUsrId'},
			{name: 'mesSubject'},
			{name: 'mesMessage'},
			{name: 'mesCreatedate'},
			{name: 'mesReaddate'},
			{name: 'mesReaddateRaw'},
			{name: 'mesLastupd'},
			{name: 'mesFileName'},
			{name: 'mesFileNameOriginal'},
			{name: 'senderUsrDel'},
			{name: 'senderUsrEmail'},
			{name: 'readerUsrDel'},
			{name: 'readerUsrEmail'},
			{name: 'insName'},
			{name: 'insUrlName'},
			{name: 'senderFullname'},
			{name: 'senderIsIns'},
			{name: 'readerFullname'},
			{name: 'readerIsIns'}
		]);

		var store = new Ext.data.GroupingStore({
			reader: reader,
			data: [
				<?
					$first = TRUE;
					foreach($getMessage as $uniqueId => $messages) {
						foreach($messages as $ii => $d) {
							echo	((!$first)?(","):(""))."[\"".$this->db->escape_str($d["mesId"])."\", \"".$this->db->escape_str($uniqueId)."\", \"".$this->db->escape_str($d["mesSenderUsrId"])."\", \"".$this->db->escape_str($d["mesInsId"])."\", \"".$this->db->escape_str($d["mesReaderUsrId"])."\", \"".$this->db->escape_str($d["mesSubject"])."\", \"".$this->db->escape_str($d["mesMessage"])."\", \"".$this->db->escape_str($d["mesCreatedate"])."\", \"".$this->db->escape_str($d["mesReaddate"])."\", \"".$this->db->escape_str($d["mesReaddateRaw"])."\", \"".$this->db->escape_str($d["mesLastupd"])."\", \"".$this->db->escape_str($d["mesFileName"])."\", \"".$this->db->escape_str($d["mesFileNameOriginal"])."\", \"".$this->db->escape_str($d["senderUsrDel"])."\", \"".$this->db->escape_str($d["senderUsrEmail"])."\", \"".$this->db->escape_str($d["readerUsrDel"])."\", \"".$this->db->escape_str($d["readerUsrEmail"])."\", \"".$this->db->escape_str($d["insName"])."\", \"".$this->db->escape_str($d["insUrlName"])."\", \"".$this->db->escape_str($d["senderFullname"])."\", \"".$this->db->escape_str($d["senderIsIns"])."\", \"".$this->db->escape_str($d["readerFullname"])."\", \"".$this->db->escape_str($d["readerIsIns"])."\"]";
							$first = FALSE;
						}
					}
				?>
			],
			sortInfo:{field: 'mesCreatedate', direction: "ASC"},
			groupField:'mesUniqueId'
		});

		var grid = new Ext.grid.GridPanel({
			store: store,
			id: 'gridMessages',
			viewConfig:{
				emptyText: '<?=$this->db->escape_str($this->lang->line("THERE_IS_CURRENTLY_NO_DATA_TO_DISPLAY"))?>'
			},

			view: new Ext.grid.GroupingView({
				forceFit:true,
				startCollapsed: true,
				emptyGroupText: '<?=$this->db->escape_str($this->lang->line("THERE_IS_CURRENTLY_NO_DATA_TO_DISPLAY"))?>',
				groupTextTpl: '{[ values.rs[0].data["mesSubject"] ]} ({[values.rs.length]} {["<?=$this->db->escape_str($this->lang->line("MESSAGES"))?>"]})'
			}),

			columns: [
				{id:'mesUniqueId', hidden: true, header: '<?=$this->db->escape_str($this->lang->line("SUBJECT"))?>', width: 100, sortable: false,  dataIndex: 'mesUniqueId'},
				{id:'mesSubject', hidden: true, header: '<?=$this->db->escape_str($this->lang->line("SUBJECT"))?>', width: 100, sortable: true,  dataIndex: 'mesSubject'},
				{id:'mesMessage', header: '<?=$this->db->escape_str($this->lang->line("MESSAGE"))?>', width: 300, sortable: true, dataIndex: 'mesMessage'},
				{header: '<?=$this->db->escape_str($this->lang->line("SENDER"))?>', width: 70, sortable: true, dataIndex: 'senderUsrEmail', renderer: function(val, cell, record) {
					return ((record.data.senderFullname != '')?(record.data.senderFullname):(val.split('@')[0] + '@'));
				}},
				{header: '<?=$this->db->escape_str($this->lang->line("CREATED_AT"))?>', width: 50, sortable: true, dataIndex: 'mesCreatedate'},
				{header: '<?=$this->db->escape_str($this->lang->line("FILE"))?>', width: 30, sortable: true, dataIndex: 'mesFileName', renderer: function(val, cell, record) {
					if(val) {
						return '<img src="<?=MEDIA?>icon/attach.png" alt="" onclick="window.open(\'<?=base_url()?>messages/download/' + record.data.mesFileName + '\')" />';
					} else {
						return '-';
					}
				}}
			],
			stripeRows: true,
			autoExpandColumn: 'mesMessage',
			autoHeight: true,
			autoWidth: true,
			enableDragDrop: false,
			sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
			listeners: {
			
				viewready: function(grid) {
					if(grid.store.getCount() == 0) {
						grid.view.mainBody.update('<div class="x-grid-empty">' + grid.viewConfig.emptyText + '</div>');
					}
				},

				rowdblclick: function(grid, rowIndex, event) {
					if(rowIndex != 'new') {
						var record = grid.getStore().getAt(rowIndex);
					} else {
						var record = new Object();
						record.data = new Object();
						record.data.mesUniqueId = Ext.getCmp('gridMessages').getSelectionModel().getSelected().data.mesUniqueId;
						record.data.mesInsId = Ext.getCmp('gridMessages').getSelectionModel().getSelected().data.mesInsId;
					}

					if(winMessages) {
						winMessages.close();
					}
					winMessages = new Ext.Window({
						iconCls: (rowIndex == 'new')?('application_form_add'):('application_form_edit'),
						layout:'',
						bodyStyle: 'background-color:white',
						autoScroll: true,
						modal: true,
						width:500,
						floating: true,
						minWidth: 500,
						height:400,
						minHeight: 400,
						closeAction:'close',
						maximizable:true,
						title: (rowIndex == 'new')?('<?=$this->db->escape_str($this->lang->line("ADD_NEW_MESSAGE"))?>'):('<?=$this->db->escape_str($this->lang->line("EDIT_MESSAGE"))?>'),

						listeners: {
							close: function() {
								Ext.getCmp('tabs').getActiveTab().getUpdater().refresh();
							}
						},

						items:[{

									border: false,

									items: messageForm = new Ext.FormPanel({
										id: 'messageForm',
										fileUpload: true,
										padding: 10,
										labelAlign: 'right',
										labelWidth: 110,
										autoHeight: true,
										autoWidth: true,
										border: false,
										defaultType: 'textfield',
										waitMsgTarget: true,
										items: [{
													hidden: true,
													inputType: 'hidden',
													name: 'mesId',
													value: record.data.mesId
											}, {
													hidden: true,
													inputType: 'hidden',
													name: 'admin',
													value: 1
											}, {
													hidden: true,
													inputType: 'hidden',
													name: 'uniqueId',
													value: record.data.mesUniqueId
											}, {
													hidden: true,
													inputType: 'hidden',
													name: 'insId',
													value: record.data.mesInsId
											}, {
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("MESSAGE"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [{
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("MESSAGE"))?>',
													xtype: 'textarea',
													name: 'message',
													value: record.data.mesMessage,
													height: 200,
													allowBlank: false,
													blankText: '<?=$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))?>',
													anchor:'100%'
												}]
											}, {
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("FILE"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [
													{
														xtype: 'fileuploadfield',
														id: 'form-file',
														emptyText: '<?=$this->db->escape_str($this->lang->line("SELECT_A_FILE"))?>',
														fieldLabel: '<?=$this->db->escape_str($this->lang->line("FILE"))?>',
														name: 'Filedata',
														buttonText: '',
														anchor:'100%',
														buttonCfg: {
															iconCls: 'upload-icon'
														}
													}
												]
											}
										]

									})

								}

							],

							bbar: {
								items: [{
									text: '<?=$this->db->escape_str($this->lang->line("SAVE"))?>',
									handler: save,
									icon: '<?=MEDIA?>icon/disk.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("CANCEL"))?>',
									handler: close,
									icon: '<?=MEDIA?>icon/cancel.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("RESET"))?>',
									handler: function() {
										messageForm.getForm().reset();
									}
								}],
								buttonAlign : 'right'
							}

					});
					winMessages.show(this);
				}

			},

			border: false,
			frame:false,

			tbar: {
				items: [{
						icon: '<?=MEDIA?>icon/application_form_add.png',
						text: '<?=$this->db->escape_str($this->lang->line("ADD_NEW_MESSAGE"))?>',
						ref: '../addBtn',
						disabled: true,
						handler: function(){
							grid.fireEvent('rowdblclick', grid, 'new', new Object());
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/application_form_delete.png',
						text: '<?=$this->db->escape_str($this->lang->line("DELETE"))?>',
						ref: '../removeBtn',
						disabled: true,
						handler: function(){
							Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_DELETE_THE_MESSAGE"))?> ' , function(btn) {
								if(btn == 'yes') {
									Ext.Ajax.request({url: '<?=site_url()?>messages/message_insert_update', params: 'del=1&mesId=' + grid.getSelectionModel().getSelections()[0].data.mesId, success: function() {
										Ext.get('center').load({url: '<?=site_url()?>admin/messages', scripts:true});
										}
									});
								}
							});
						}
					}
				]
			}

		});

		grid.render('grid-table-messages');

		grid.getSelectionModel().on('selectionchange', function(sm){
			grid.removeBtn.setDisabled(sm.getCount() < 1);
			grid.addBtn.setDisabled(sm.getCount() < 1);
		});

		function save() {
			if(!messageForm.getForm().isValid()) {
				Ext.Msg.show({
					title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
					msg: '<?=$this->db->escape_str($this->lang->line("PLEASE_CORRECT_THE_ERRORS"))?>',
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.WARNING
				});
			} else {
				if(messageForm.getForm().isDirty()) {
					messageForm.getForm().submit({
						url: '<?=site_url()?>messages/',
						method: 'POST',
						success: function(form, resp) {
							if(resp.result.error) {
								Ext.Msg.show({
									title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
									msg: resp.result.error,
									buttons: Ext.Msg.OK,
									icon: Ext.MessageBox.ERROR
								});
							} else {
								winMessages.close();
							}
						},
						failure: function(form, action) {
							
						}
					});
				} else {
					winMessages.close();
				}
			}
		};

		function close() {
			winMessages.close();
		};

	})
</script>


<div id="grid-table-messages"></div>